﻿// “项目页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234233 上提供

namespace Manhua2.Pages
{
    using Manhua2.Common;
    using Manhua2.DataModel;
    using Manhua2.Provider;
    using NotificationsExtensions.TileContent;
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Threading;
    using System.Threading.Tasks;
    using Windows.Storage;
    using Windows.Storage.Pickers;
    using Windows.UI.Notifications;
    using Windows.UI.Popups;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Navigation;
    using Manhua2.Helper;

    /// <summary>
    /// 显示项预览集合的页。在“拆分布局应用程序”中，此页
    /// 用于显示及选择可用组之一。
    /// </summary>
    public sealed partial class MainPage : Manhua2.Controls.LayoutAwarePage
    {
        private CancellationTokenSource cts = new CancellationTokenSource();

        public MainPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// 使用在导航过程中传递的内容填充页。在从以前的会话
        /// 重新创建页时，也会提供任何已保存状态。
        /// </summary>
        /// <param name="navigationParameter">最初请求此页时传递给
        /// <see cref="Frame.Navigate(Type, Object)"/> 的参数值。
        /// </param>
        /// <param name="pageState">此页在以前会话期间保留的状态
        /// 字典。首次访问页面时为 null。</param>
        protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            string error = null;
            try
            {
                NetworkState state = NetworkHelper.GetNetworkState();
                this.DefaultViewModel["Progress"] = true;

                this.LoadHistories();
                if (state == NetworkState.None)
                    throw new Exception("无法连接到网络...");

                if (state == NetworkState.Unlimited)
                {
                    await this.LoadComicsAsync(true);
                }
                else
                {
                    await MethodHelper.ShowMessageDialog("您正在使用流量计费网络, 请手动刷新最新漫画。");
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }

            await MethodHelper.ShowMessageDialogNotEmpty(error);

            this.DefaultViewModel["Progress"] = false;
            this.DefaultViewModel["IsBtnEnabled"] = true;

            await this.DownloadCoverCacheAsync();
        }
                
        private async Task LoadLatestComics(IComicProvider provider)
        {
            using (ModelContext context = new ModelContext())
            {
                this.DefaultViewModel["comics"] = await context.QueryLatestComicsAsync(provider);
            }
        }

        private async void LoadHistories()
        {
            using (ModelContext context = new ModelContext())
            {
                this.DefaultViewModel["histories"] = await context.QueryHistoriesAsync(9);
            }
        }

        private async Task DownloadCoverCacheAsync()
        {
            try
            {
                var histories = (ObservableCollection<ComicItem>)this.DefaultViewModel["histories"];
                var comics = (ObservableCollection<ComicItem>)this.DefaultViewModel["comics"];

                // 历史记录封面
                foreach (var item in histories)
                {
                    try
                    {
                        if (string.IsNullOrEmpty(item.Cover))
                        {
                            CoverCacheManager.DownloadCoverAsync(item);
                        }
                    }
                    catch
                    {
                    }
                }

                // 最新更新封面
                foreach (var item in comics)
                {
                    try
                    {
                        if (string.IsNullOrEmpty(item.Cover))
                        {
                            CoverCacheManager.DownloadCoverAsync(item);
                        }
                    }
                    catch
                    {
                    }
                }
            }
            catch
            {
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GridView_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.NavigateToViewPage(e.ClickedItem as ComicItem);
        }

        private void ListView_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.NavigateToViewPage(e.ClickedItem as ComicItem);
        }

        protected override void OnNetworkStatusChanged(NetworkState state)
        {
        }

        /// <summary>
        /// 加载最新漫画
        /// </summary>
        /// <param name="refresh"></param>
        /// <returns></returns>
        private async Task LoadComicsAsync(bool refresh)
        {
            // 此处使用默认漫画源
            IComicProvider provider = ComicProviderFactory.Create(Global.ClientOption.DefaultProviderName);
            await provider.SaveLatestComicsAsync(refresh);
            await this.LoadLatestComics(provider);
            await DownloadCoverCacheAsync();
        }

        private async void btnRefresh_Click(object sender, RoutedEventArgs e)
        {
            this.DefaultViewModel["comics"] = null;
            this.DefaultViewModel["IsBtnEnabled"] = false;
            this.DefaultViewModel["Progress"] = true;

            string error = null;

            try
            {
                await this.LoadComicsAsync(false);
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }


            this.DefaultViewModel["IsBtnEnabled"] = true;
            this.DefaultViewModel["Progress"] = false;

            await MethodHelper.ShowMessageDialogNotEmpty(error);
        }

        private async void btnOpen_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new MessageDialog(
                "1. 打开目录下的所有图片文件(建议使用此方式管理文件)\r\n" +
                "2. 打开zip或rar压缩包中的图片文件(不支持密码)\r\n" +
                "注意, 图片加载是一次性加载, 请不要打开过于庞大的文件或文件夹.",
                "提示");

            dialog.Commands.Add(new UICommand("打开目录", (cmd) => { }, 1));
            dialog.Commands.Add(new UICommand("打开文件", (cmd) => { }, 2));
            dialog.Commands.Add(new UICommand("取消", (cmd) => { }, 3));

            var command = await dialog.ShowAsync();
            switch ((int)command.Id)
            {
                case 1:
                    {
                        FolderPicker picker = new FolderPicker();
                        picker.FileTypeFilter.Add(".jpg");
                        picker.FileTypeFilter.Add(".bmp");
                        picker.FileTypeFilter.Add(".png");
                        var folder = await picker.PickSingleFolderAsync();
                        if (folder != null)
                        {
                            Global.FileProvider = new Provider.LocalFileProvider(folder);
                            this.Frame.Navigate(typeof(LocalFileViewPageNew));
                        }
                    }

                    break;

                case 2:
                    {
                        FileOpenPicker picker = new FileOpenPicker();
                        picker.FileTypeFilter.Add(".zip");
                        picker.FileTypeFilter.Add(".rar");

                        var file = await picker.PickSingleFileAsync();
                        if (file != null)
                        {
                            Global.FileProvider = new Provider.LocalFileProvider(file);
                            this.Frame.Navigate(typeof(LocalFileViewPageNew));
                        }
                    }
                    break;

                default:
                    break;
            }
        }

        private void btnHelp_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(HelpPage));
        }

        private void btnDownload_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(DownloadPage));
        }

        private void btnFavorite_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(FavoritePage));
        }

        private void NavigateToViewPage(ComicItem item)
        {
            if (item == null) return;
            this.Frame.Navigate(typeof(ViewPageNew), item.Chapter.Id);
        }
    }
}
